<?php
namespace Todo\Model\Base;

use Todo\Model\BaseModel;
use Todo\Service\DictService;

class DepartmentModel extends BaseModel
{
    public $tableName = 'base_department';

    public $_validate = array(
        array('title', 'require', '请输入部门名称'),
        array('title','1,50','名称长度超出限制！',1,'length')
    );

    protected $_auto = array(
        array('master_user', '_master', self::MODEL_BOTH, 'callback'),
        array('tnt_id', 'auto_tnt', self::MODEL_INSERT, 'function')
    );

    protected function _master(){
        $master = I('post.master');
        if(!$master) return 0;
        
        return D('Todo/Base/Teacher')->findOne(array('tnt_id'=>TNT_ID,'number'=>$master), 'user_id');
    }

    /**
     * 导入一行数据
     * @param $row 数据
     * @param int $exists=1 数据冲突处理方式：1报错，2跳过，3覆盖
     * @return bool
     */
    public function importOne($row, $exists=1){
        if(count($row) < 2 || !$row[0] || !$row[1]){
            $this->error = "部门名称和类型不能为空";
            return false;
        }
        $data = array(
            'title' => $row[0]
        );
        $data['type'] = DictService::getInstance()->getDictValue('DEPARTMENT_TYPE', $row[1]);
        if(count($row)>2 && $row[2]) {// 上级部门
            $data['pid'] = D('Todo/Base/Department')->where(array('title'=>$row[2]))->cache(true)->getField('id');
        }else{
            $data['pid'] = 0;
        }
        if(count($row)>3 && $row[3]) {// 状态
            $data['status'] = DictService::getInstance()->getDictValue('STATUS', $row[3]);
        }else{
            $data['status'] = '1';
        }
        if(count($row)>4 && $row[4]) {// 部门负责人
            $info = D('Todo/Base/Teacher')->findOne(array('tnt_id'=>TNT_ID,'number'=> $row[4]));
            if(!$info || $info['name'] != $row[5]){
                $this->error = '部门负责人('.$row[4].':'.$row[5].')不存在';
                return false;
            }
            $data['master_user'] = $info['user_id'];
        }else{
            $data['master_user'] = 0;
        }
        if(count($row)>6 && $row[6]) $data['sort'] = $row[6]; //排序
        $old = $this->where(array('title' => $row[0]))->find();
        if($old){ //部门名称已存在
            if($exists == 1) {
                $this->error = '名称为（'.$row[0].'）的部门信息已经存在';
                return false;
            }else if($exists == 2) return true;
            else{
                $old = array_merge($old, $data);
                return $this->save($old) !== false;
            }
        }else{ //部门不存在
            return $this->add($data);
        }
    }

    /**
     * 导出Excel
     * @param $list array 数据列表
     * @param $excel ExcelUtil Excel操作对象
     */
    public function exports($list, $excel){
        $title = array(
            'title'=>'部门名称',
            'type'=>'部门类型',
            'pid'=>'上级部门',
            'number'=>'部门负责人工号',
            'name'=>'负责人姓名',
            'status'=>'状态',
            'sort'=>'排序'
        );
        foreach ($list as &$row){
            if($row['type']) $row['type'] = DictService::getInstance()->getDictTitle('DEPARTMENT_TYPE', $row['type']);
            else $row['type'] = '';

            if($row['pid']) $row['pid'] = D('Todo/Base/Department')->keyFind($row['pid'], 'title');
            else $row['pid'] = '';

            if($row['master_user']){
                $teacher = D('Todo/Base/Teacher')->findByField('user_id', $row['master_user']);
                if($teacher){
                    $row['number'] = $teacher['number'];
                    $row['name'] = $teacher['name'];
                }
            }

            if($row['status']) $row['status'] = DictService::getInstance()->getDictTitle('STATUS', $row['status']);
            else $row['status'] = '';
        }
        $excel->exportExcel("部门", $title, $list);
    }
}